/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/
const PENDING = 'pending';      // 等待
const FULFILLED = 'fulfilled';  // 成功
const REJECTED = 'rejected';    // 失败

class MyPromise {
    constructor (executor) {
        try {
            executor(this.resolve, this.reject)
        } catch(e) {
            this.reject(e)
        }
    }
    status = PENDING; // 状态
    value = undefined; // 成功的值
    reason = undefined; //失败的值
    successCallback = []; //储存成功的回调函数
    failCallback = []; //储存失败的回调函数
    resolve = value => {
        if (this.status !== PENDING) return;
          this.status = FUFILLED;
          this.value = value;
          if (this.successCallback.length != 0) {
            //判断储存的数组有没有成功回调函数 如果有就循环调用 调用一个删除一个
            // this.successCallback.shift()(value)
            this.successCallback.forEach((item) => {
              let x = item();
            });
          }
          this.successCallback = [];
    }
    reject = (reason) => {
        if (this.status !== PENDING) return;
        this.status = REJECTED;
        this.reason = reason;
        if (this.failCallback.length != 0) {
          // 判断失败回调是否存在 如果存在 调用
          for (let i = 0; i < this.failCallback.length; i++) {
            // let y=this.failCallback[i](reason)
            let x = this.failCallback[i]();
          }
          this.failCallback = [];
        }
    }
    then(succsessCallback, failCallback) {
        succsessCallback = succsessCallback
            ? succsessCallback
            : (value) => value;
          failCallback = failCallback
            ? failCallback
            : (reason) => {
                throw reason;
              };
          let promise2 = new MyPromise((resolve, reject) => {
            //   判断状态
            if (this.status == FUFILLED) {
              setTimeout(() => {
                console.log("FUFILLED");
                try {
                  let x = succsessCallback(this.value);
                  resolvePromsise(promise2, x, resolve, reject);
                } catch (e) {
                  reject(e);
                }
              }, 0);
            } else if (this.status == REJECTED) {
              console.log("REJECTED");
              setTimeout(() => {
                try {
                  let y = failCallback(this.reason);
                  resolvePromsise(promise2, y, resolve, reject);
                } catch (e) {
                  reject(e);
                }
              });
            } else {
                // 将成功回调和失败回调储存起来
              this.successCallback.push(() => {
                setTimeout(() => {
                  console.log("FUFILLED");
                  try {
                    let x = succsessCallback(this.value);
                    resolvePromsise(promise2, x, resolve, reject);
                  } catch (e) {
                    reject(e);
                  }
                }, 0);
              });
              this.failCallback.push(() => {
                setTimeout(() => {
                  try {
                    let y = failCallback(this.reason);
                    resolvePromsise(promise2, y, resolve, reject);
                  } catch (e) {
                    reject(e);
                  }
                });
              });
            }
          });

          return promise2;
    }
    finally(callback) {
        return this.then(
          (value) => {
            // callback()
            return MyPromise.resolve(callback()).then(() => value);
          },
          (reason) => {
            // callback()
            return MyPromise.resolve(callback()).then(() => {
              throw reason;
            });
          }
        );
    }
    catch(failCallback) {
        return this.then(undefined, failCallback)
    }
    static all (array) {
        let result = [];
        let index = 0;
        return new MyPromise((resolve, reject) => {
          function addData (key, value) {
            result[key] = value;
            index++;
            if (index === array.length) {
              resolve(result);
            }
          }
          for (let i = 0; i < array.length; i++) {
            let current = array[i];
            if (current instanceof MyPromise) {
                // promise 对象
                current.then(
                    (value) => {
                    addData(i, value);
                    },
                    (reason) => {
                    reject(reason);
                    }
                );
            }else {
                // 普通值
                addData(i, array[i]);
            }
          }
        })
    }
    static resolve (value) {
        if (value instanceof MyPromise) {
            return value;
        } else {
            return new MyPromise((resolve, reject) => {
              resolve(value);
            });
        }
    }
}
    
function resolvePromise(promsie2, x, resolve, reject) {
    if (promsie2 === x) {
        return reject(new TypeError('报错信息'))
    }
    if (x instanceof MyPromise) {
        // promise 对象
        x.then(value => resolve(value), reason => reject(reason));
    } else {
        // 普通值
        resolve(x);
    }

}


module.exports = MyPromise;